// this program will use with min.sh and usr1.sh

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
using namespace std;

int g_unreliable = 0;
int g_reliable = 0;

void signal_dispatch(int signo){
    if(signo == SIGUSR1){
        cout << "receving signal SIGUSR1" << endl;
        g_unreliable++;
    }
    else if(signo == SIGRTMIN){
        cout << "receving signal SIGRTMIN" << endl;
        g_reliable++;
    }
}

void output(){
    cout << "++++++++++++++++++++++++++++++++" << endl;
    cout << "++++++++++hello world+++++++++++" << endl;
    cout << "++++++++++i am lancer+++++++++++" << endl;
    cout << "++++++++++++++++++++++++++++++++" << endl;
}

int main(int argc, char** argv){
    if(argc != 1){
        cout << "this program don't need any paramter" << endl;
        return 0;
    }

    output();
    if(signal(SIGUSR1, signal_dispatch) == SIG_ERR){
        perror("register SIGUSR1 signal failed");
        return -1;
    }
    if(signal(SIGRTMIN, signal_dispatch) == SIG_ERR){
        perror("register SIGRTMIN signal failed");
        return -1;
    }

    sigset_t set;
    sigset_t old;

    sigemptyset(&set);

    sigaddset(&set, SIGUSR1);
    sigaddset(&set, SIGRTMIN);

    if(sigprocmask(SIG_BLOCK, &set, &old) == -1){
        perror("set process signal to be set failed");
        return -1;
    }
    
    sleep(20);

    if(sigpending(&set) == -1){
        perror("sigpending get set mask failed");
        return -1;
    }

    int ret = -1;
    if((ret = sigismember(&set, SIGUSR1)) == -1){
        perror("sigismember test SIGUSR1 failed");
        return -1;
    }
    else if(ret == 0){
        cout << "SIGUSR1 signal exist not signal mask" << endl;
    }
    else{
        cout << "SIGUSR1 signal exist signal mask" << endl;
    }

    if((ret = sigismember(&set, SIGRTMIN)) == -1){
        perror("sigismember test SIGRTMIN failed");
        return -1;
    }
    else if(ret == 0){
        cout << "SIGRTMIN signal exist not signal mask" << endl;
    }
    else{
        cout << "SIGRTMIN signal exist signal mask" << endl;
    }

    sleep(30);

    if(sigprocmask(SIG_SETMASK, &old, NULL) == -1){
        perror("set oldset failed");
        return -1;
    }

    cout << "SIGUSR1:\t" << g_unreliable << endl;
    cout << "SIGRTMIN:\t" << g_reliable << endl;
    output();
    return 0;
}